import KoaRouter from 'koa-router'
import { Models } from '@/common/typings/modle'
import { command } from '@/server/mysql'
import { QueryFailed, Success } from '@/core/HttpException'
import Config from '@/config/Config'
import { Account } from '@/common/typings/account'
import verifyToken from '@/middlewares/verifyToken'
import { getRoleList } from '@/api/v1/system/role/list'
import { isAdmin } from '@/api/v1/system/role/isAdmin'

const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v1/system/auth`,
})

router.get('/currentUser', verifyToken, async (ctx: Models.Ctx) => {
  const auth = ctx.auth
  if (auth && auth.id) {
    const res: Models.Result = await command(`SELECT * FROM system_user WHERE id = '${auth.id}';`)
    if ((res.results as Account.User[]).length > 0) {
      const user = res.results[0]
      const ia = await isAdmin(ctx)
      const { finallyResult } = await getRoleList({ userList: [user.id], ia })
      const resourceInfoList: any[] = []
      const roleInfoList = finallyResult.map((item) => {
        const { userList, resourceList, ...roleItem } = item
        ;(resourceList || []).forEach((resource: any) => {
          if (!resourceInfoList.some((r) => r.uniqueProp === resource.uniqueProp)) {
            resourceInfoList.push(resource)
          }
        })
        return {
          ...roleItem,
        }
      })
      throw new Success({
        data: {
          ...user,
          roleInfoList,
          isAdmin,
          resourceInfoList,
        },
      })
    }
  } else {
    throw new QueryFailed({ msg: '用户名或密码错误' })
  }
})
export default router
